package com.uni.support;

import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import com.uni.common.util.ReturnData;


@ControllerAdvice
public class CommonExceptionHandler {

	@ExceptionHandler(MyException.class)
	@ResponseBody
	public ReturnData exceptionHandler(MyException e) {
		ReturnData rd = new ReturnData();
		return rd.failBack(e.getMessage());
	}
	
	@ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
	@ResponseBody
    public ReturnData validationError(MethodArgumentNotValidException ex) {
		ReturnData rd = new ReturnData();
        FieldError fieldError = ex.getBindingResult().getFieldError();
        return rd.failBack(fieldError.getField()+fieldError.getDefaultMessage());
    }
	
	@ExceptionHandler(BindException.class)
	@ResponseBody
    public ReturnData bindException(BindException ex) {
		ReturnData rd = new ReturnData();
        FieldError fieldError = ex.getBindingResult().getFieldError();
        return rd.failBack(fieldError.getField()+fieldError.getDefaultMessage());
    }
}
